package com.yunkaweilai.android.net;

import android.os.Handler;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.internal.Primitives;
import com.orhanobut.logger.Logger;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.model.CodeMsgBean;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Post请求处理
 * <p>
 * Created by Leu on 2017/2/26.
 */

public class PostProcess {
    private static Handler handler = new Handler();
    private PostFormBuilder mPostFormBuilder = null;
    private static String mTag = "PostProcess";
    private String mParam = "请求参数：";
    protected Map<String, String> params = new HashMap<String, String>();

    PostProcess(String url) {
        this.mPostFormBuilder = OkHttpUtils
                .post()
                .url(url);
    }

    PostProcess() {
        this.mPostFormBuilder = OkHttpUtils
                .post()
                .url(CommonConstants.BASE_URL);
    }

    /**
     * 添加参数，setAction之后调用
     *
     * @param key
     * @param val
     * @return
     */
    public PostProcess addParams(String key, String val) {
        params.put(key, val);
        return this;
    }

    /**
     * 如果调用这个方法，就会打印返回的数据
     * 在execute()之前调用有效
     *
     * @param tag
     * @return
     */
    public PostProcess log(String tag) {
        mTag = tag;
        return this;
    }

    private void getParams() {
        TreeMap treeMap = new TreeMap<String, String>(params);
        Set<Map.Entry<String, String>> entries = treeMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            mParam = mParam + entry.getKey() + "=" + entry.getValue() + ";";
        }
        mPostFormBuilder.params(params);
    }


    /**
     * 返回一段json ,加如了token，公共参数
     *
     * @param stringCallBack
     */
    public PostProcess execute(final StringCallBack stringCallBack) {
        getParams();
        logParam(mTag, mParam);
        mPostFormBuilder
                .addParams("token", BaseApplication.getToken())
                .addParams("member_from", "MemberFromAndroid")
                .addParams("login_source", "Android")
                .addParams("version_code", BaseApplication.APP_CODE + "")
                .build()
                .execute(new GetMsgCallback2() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        stringCallBack.onError(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        stringCallBack.onResponse(response);
                    }
                });
        return null;
    }

    /**
     * 返回一段json ,加如了token，公共参数
     * 复制上面的 用于搜索会员的时候不添加member_from字段
     * @param stringCallBack
     */
    public PostProcess executeSearchMember(final StringCallBack stringCallBack) {
        getParams();
        logParam(mTag, mParam);
        mPostFormBuilder
                .addParams("token", BaseApplication.getToken())
                .addParams("login_source", "Android")
                .addParams("version_code", BaseApplication.APP_CODE + "")
                .build()
                .execute(new GetMsgCallback2() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        stringCallBack.onError(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        stringCallBack.onResponse(response);
                    }
                });
        return null;
    }

    /**
     * 返回一段json ,仅添加token，公共参数
     * @param stringCallBack
     */
    public PostProcess executeToken(final StringCallBack stringCallBack) {
        getParams();
        logParam(mTag, mParam);
        mPostFormBuilder
                .addParams("token", BaseApplication.getToken())
                .build()
                .execute(new GetMsgCallback2() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        stringCallBack.onError(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        stringCallBack.onResponse(response);
                    }
                });
        return null;
    }    /**
     * 返回一段json
     * @param stringCallBack
     */
    public PostProcess executeNoToken(final StringCallBack stringCallBack) {
        getParams();
        logParam(mTag, mParam);
        mPostFormBuilder
                .build()
                .execute(new GetMsgCallback2() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        stringCallBack.onError(e);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        stringCallBack.onResponse(response);
                    }
                });
        return null;
    }


    /**
     * 只有此方法是同步请求，其他都是异步的
     */
    public Response executeSync() {
        logParam(mTag, mParam);
        try {
            return mPostFormBuilder
                    .build()
                    .execute();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }


    /**
     * 进入登录界面
     */
    private static void gotoLogin() {
//        Intent intent = new Intent(BaseApplication.getInstance(), MyLoginCodeActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        BaseApplication.getInstance().startActivity(intent);
    }

    /**
     * 有数据返回时的网络回调，封装了自动Bean类型生成
     * <p>
     * Created by Administrator on 2017-02-23.
     */

    public abstract static class BeanCallBack<T> extends Callback<T> {
        private Class<T> tempClass = null;

        public BeanCallBack(Class<T> classOfT) {
            tempClass = classOfT;
        }

        @Override
        public T parseNetworkResponse(Response response, int id) throws IOException {
            String string = response.body().string();
            return (T) getObject(string, tempClass);
        }

        public <T> T getObject(String data, Class<T> classOfT) {
            Gson gson = new Gson();
            Object obj = gson.fromJson(data, classOfT);
            return Primitives.wrap(classOfT).cast(obj);
        }
    }

    /**
     * 不需要数据返回的网络回调，提示请求完成
     * <p>
     * Created by Leu on 2017/2/26.
     */
    public interface SimpleCallBack {
        void onResponse(CodeMsgBean codeMsgBean);

        void onError(Exception e);
    }

    public interface StringCallBack {
        void onResponse(String json);

        void onError(Exception e);
    }

    public interface SCallBack<T> {
        void onResponse(T codeMsgBean);

        void onError(Exception e);
    }

    /**
     * 打印发送参数
     *
     * @param mTag
     * @param mParam
     */
    private void logParam(String mTag, String mParam) {
        if (!TextUtils.isEmpty(mTag)) {
            Logger.t(mTag).e(mParam);
        }
    }

    /**
     * 打印返回数据
     *
     * @param mTag
     * @param mParam
     */
    private static void logData(String mTag, String mParam) {
        if (!TextUtils.isEmpty(mTag)) {
            Logger.t(mTag).e(mParam);
            Logger.t(mTag).json(mParam);
        }
    }

    private abstract class GetMsgCallback extends Callback<CodeMsgBean> {
        @Override
        public CodeMsgBean parseNetworkResponse(Response response, int id) throws IOException {
            String string = response.body().string();
            logData(mTag, string);
            return new Gson().fromJson(string, CodeMsgBean.class);
        }
    }

    private abstract class GetMsgCallback2 extends Callback<String> {
        @Override
        public String parseNetworkResponse(Response response, int id) throws IOException {
            String string = response.body().string();
            logData(mTag, string);
            return string;
        }
    }


}
